package com.yonyou.brigade.third_parties.zteitc.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;


/**
 * 加密工具类
 *
 * @author zte
 *
 */
public class Md5Encrypt {
    private static final ThreadLocal<Md5Encrypt> local = new ThreadLocal<Md5Encrypt>();

    private Md5Encrypt() {
        super();
    }

    public static Md5Encrypt getEncrypt() {
        Md5Encrypt encrypt = local.get();
        if (encrypt == null) {
            encrypt = new Md5Encrypt();
            local.set(encrypt);
        }
        return encrypt;
    }

    /**
     * md5加密key
     *
     * @param
     * @return
     */
    public String encode(String key) {
        if (key == null) {
            return null;
        }
        return DigestUtils.md5Hex(key);
    }

    /**
     * 测试供应商那边加密算法
     *
     * @param args
     */
    public static void main(String args[]) {

        String xml = "<Request><Dpt>SZX</Dpt><Arr>SYX</Arr><Date>2011-02-25</Date><Airline>HU</Airline></Request>";

        String md5 = Md5Encrypt.getEncrypt().encode(xml + Md5Encrypt.getEncrypt().encode("85775555"));

        System.out.println("QingDao： 0f96e33688bf3b190393049d0017038d");

        System.out.println("WangXin：" + md5);

    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f" };
}
